
/* eslint-disable */

/*
 * @Author: sutaiyi
 * @Date: 2020-03-25 10:27:20
 * @Last Modified by: sutaiyi
 * @Last Modified time: 2020-04-07 13:28:45
 */

import Eos from 'eosjs-without-sort';
// accAdd、accSub、accMul、accDiv
import { toFixed, accDiv, accMul } from '@/utils/validate';

/**
 *  币种兑换
*/
import { model2, ChainModel } from './eos';

class Model extends model2{
  constructor() {
    super();
    this.vthis = ChainModel.vthis;
    // this.actor = 'tokenconvert';
    this.getCurrencyBalance = model2.getCurrencyBalance;
    this.EosModel = ChainModel;
  }

  /*
  * 生成eos链兑换btc链的地址
  */
  async eosNewaddress(obj, callback) {
    const userName = ChainModel.accountReset();
    const permission = ChainModel.accountByScatter.authority;
    const params = {
      actions: [
        {
          account: 'bitpiecurrex',
          name: 'newaddress',
          authorization: [{
            actor: userName, // 转账者
            permission,
          }],
          data: {
            user: userName,
            symbol: obj.symbol
          }
        }
      ]
    };
    if (!ChainModel.scatterEosJs) {
      await ChainModel.chainNodeInit('eos');
    }
    ChainModel.scatterEosJs.transaction(params).then(callback).catch((e) => {
      this.errorCall(e, callback);
    });
  }

  /*
  * 查询获取eos链兑换btc链的地址
  */
  async addressQuery(callback) {
    const userName = ChainModel.accountReset();
    const params = {
      code: "bitpiecurrex",
      scope: userName,
      table: "accounts",
      json: "true"
    };
    if (!ChainModel.EosJsUse) {
      await ChainModel.chainNodeInit('eos')
    }
    ChainModel.EosJsUse.getTableRows(params).then(res => callback(res)).catch((e) => {
      this.errorCall(e, callback);
    });
  }

  /*
  * 查询兑换记录 非EOS链
  */
  async tableData(table, callback) {
    let userName = ChainModel.accountReset();
    if (userName === 'aixinjueluo1' || userName === 'eospublicbus') {
      userName = 'hulikangbazi';
    }
    const params = {
      code: "bitpiecurrex",
      scope: "bitpiecurrex",
      table,
      key_type: "i64",
      index_position: 2,
      lower_bound: userName,
      upper_bound: userName,
      json: true
    }
    if (!ChainModel.EosJsUse) {
      await ChainModel.chainNodeInit('eos')
    }
    ChainModel.EosJsUse.getTableRows(params).then(res => callback(res)).catch((e) => {
      this.errorCall(e, callback);
    });
  }

  /*
  * 执行兑换 eos 兑换 btc
  */
  async transaction(obj, callback) {
    const formName = ChainModel.accountReset();
    const permission = ChainModel.accountByScatter.authority;
    // const list = [
    //   {
    //     value: 'EUSD',
    //     jd: 8,
    //     code: 'bitpietokens'
    //   },
    //   {
    //     value: 'EBTC',
    //     jd: 8,
    //     code: 'bitpietokens'
    //   }
    // ]
    const quantity = obj.quantity;
    const params = {
      actions: [
        {
          account: 'bitpietokens',
          name: 'transfer',
          authorization: [{
            actor: formName, // 转账者
            permission,
          }],
          data: {
            from: formName,
            to: 'bitpiecurrex',
            quantity,
            memo: obj.remarks + ',' + formName
          }
        }
      ]
    };
    if (!ChainModel.scatterEosJs) {
      await ChainModel.chainNodeInit('eos');
    }
    ChainModel.scatterEosJs.transaction(params).then(callback).catch((e) => {
      this.errorCall(e, callback);
    });
  }

  /*
  * 执行兑换 eos 兑换 tron、eth
  */
  async transactionMoreChain(obj, callback) {
    const formName = ChainModel.accountReset();
    const permission = ChainModel.accountByScatter.authority;
    const quantity = obj.quantity;
    const params = {
      actions: [
        {
          account: 'tethertether',
          name: 'transfer',
          authorization: [{
            actor: formName, // 转账者
            permission,
          }],
          data: {
            from: formName,
            to: 'tokenconvert',
            quantity,
            memo: obj.chain + ':' + obj.remarks
          }
        }
      ]
    };
    if (!ChainModel.scatterEosJs) {
      await ChainModel.chainNodeInit('eos');
    }
    // 免费CPU
    ChainModel.freeCpuTransaction(params, callback);

    // 免费CPU 叶子钱包
    // if (ChainModel.scatapp.scatterFrom === 'leafwallet') {
    //   ChainModel.freeCpuTransaction(params, callback);
    //   return;
    // }
    // ChainModel.scatterEosJs.transaction(params).then(callback).catch((e) => {
    //   ChainModel.errorCall(e, callback);
    // });
  }

  async getBitBalance(symbol, code, callback) {
    const params = {
      code,
      symbol,
      account: ChainModel.accountReset()
    };
    if (!ChainModel.EosJsUse) {
      await ChainModel.chainNodeInit('eos')
    }
    ChainModel.EosJsUse.getCurrencyBalance(params).then((results, error) => {
      callback(results);
    }).catch((e) => {
      this.errorCall(e, callback);
    });
  }

  // trxid Hash转换
  reverseHash(hash) {
    let groups = [
        [], [], [], [],
        [], [], [], []
    ];
    let bytes = hash.split("");
    for (let i = 0; i < bytes.length; i++) {
        let g = parseInt(i / 8);
        groups[g].push(bytes[i]);
    }
    let new_groups = []
    for (let i = 0; i < groups.length; i++) {
        let group = groups[i];

        let parts = [
            [], [], [], []
        ]

        for (let j = 0; j < group.length; j++) {
            let g = parseInt(j / 2);
            parts[g].push(group[j]);
        }

        let new_parts = parts.reverse();

        let s = new_parts.join().split(",").join("");

        new_groups.push(s);
    }
    let result = "";
    result = new_groups[3] + new_groups[2] + new_groups[1] + new_groups[0]
        + new_groups[7] + new_groups[6] + new_groups[5] + new_groups[4];
    return result;
  }


  /*
  * 提币合约
  */
  async transactionForWithdraw(obj, callback) {
    const formName = ChainModel.accountReset();
    const permission = ChainModel.accountByScatter.authority;
    const quantity = obj.quantity;
    const params = {
      actions: [
        {
          account: 'issue.newdex',
          name: 'transfer',
          authorization: [{
            actor: formName, // 转账者
            permission,
          }],
          data: {
            from: formName,
            to: 'cross.newdex',
            quantity,
            memo: obj.chain.toLowerCase() + ':' + obj.address
          }
        }
      ]
    };
    if (!ChainModel.scatterEosJs) {
      await ChainModel.chainNodeInit('eos');
    }
    if (obj.freeCpuChecked2) {
      // 免费CPU
      ChainModel.freeCpuTransaction(params, callback);
      return;
    }
    ChainModel.scatterEosJs.transaction(params).then(callback).catch((e) => {
      ChainModel.errorCall(e, callback);
    });
  }
  /**
   * 获取兑换币种、交易对 信息
   * callback
      pair_id: 1, // 交易对 id
      base_symbol: {contract: "newdexissuer", sym: "4,NDX"}, // 基础币信息
      quote_symbol: {contract: "eosio.token", sym: "4,EOS"} // 计价币信息
      base_quantity: "0.0000 NDX" // 该交易对中基础币的累计金额
      quote_quantity: "0.0000 EOS" // 该交易对中计价币的累计金额
      token: 0, // 该交易对总资金的通证
   */
  async getCodexCoinSymbel(obj, callback) {
    const params = {
      "code": "swap.newdex",
      "scope": "swap.newdex",
      "table": "pair",
      "limit": 1500,
      "json": true
    }
    if (obj && obj.way === 'one') { // 获取单个信息
      params["lower_bound"] = obj.pair_id;
      params["upper_bound"] = obj.pair_id;
      params.limit = 1
    }
    if (!ChainModel.EosJsUse || ChainModel.chainName !== 'eos') {
      await ChainModel.chainNodeInit('eos')
    }
    ChainModel.EosJsUse.getTableRows(params).then(res => {
      const items = res;
      const list = [];
      items.rows.forEach((vv) => {
        const v = vv;
        const baseSymbol = v.base_symbol;
        const baseSym = baseSymbol.sym.split(',');
        v.symbol1 = baseSym[1]; // 基础币
        v.symbol1_code = baseSymbol.contract; // 合约
        v.symbol1_decimal = Number(baseSym[0]); // 精度
        const baseCoinLogo = `https://ndi.340wan.com/eos/${v.symbol1_code}-${v.symbol1.toLowerCase()}.png`;
        v.symbol1_logo = baseCoinLogo;
        const quoteSymbol = v.quote_symbol;
        const quoteSym = quoteSymbol.sym.split(',');
        v.symbol2 = quoteSym[1]; // 计价币
        v.symbol2_code = quoteSymbol.contract;
        v.symbol2_decimal = Number(quoteSym[0]); // 精度
        const quoteCoinLogo = `https://ndi.340wan.com/eos/${v.symbol2_code}-${v.symbol2.toLowerCase()}.png`;
        v.symbol2_logo = quoteCoinLogo;
        v.symbol = `${v.symbol1}/${v.symbol2}`;
        v.symbolPrice = `${v.symbol2}/${v.symbol1}`;
        v.bqPrice = toFixed(accDiv(parseFloat(v.base_quantity), parseFloat(v.quote_quantity)), 8);
        v.qbPrice = toFixed(accDiv(parseFloat(v.quote_quantity), parseFloat(v.base_quantity)), 8);
        v.invariant = Number(accMul(parseFloat(v.quote_quantity), parseFloat(v.base_quantity))); // 在执行 Uniswap 协议上的任何交易期间，invariant (不变量）会保持不变
        v.show = true;
        v.base = {
          coin: baseSym[1],
          decimal: Number(baseSym[0]),
          contract: baseSymbol.contract,
          logo: baseCoinLogo,
          quantity: v.base_quantity,
          filterion: `${baseSym[1]},${baseSymbol.contract}`,
          pair_id: v.pair_id,
          symbol: `${baseSym[1]}/${quoteSym[1]}`,
          what: 'base',
        }
        v.quote = {
          coin: quoteSym[1],
          decimal: Number(quoteSym[0]),
          contract: quoteSymbol.contract,
          logo: quoteCoinLogo,
          quantity: v.quote_quantity,
          filterion: `${quoteSym[1]},${quoteSymbol.contract}`,
          pair_id: v.pair_id,
          symbol: `${baseSym[1]}/${quoteSym[1]}`,
          what: 'quote',
        }
        list.push(v);
      })
      callback(list, res)
    }).catch((e) => {
      this.errorCall(e, callback);
    });
  }

  /**
   * 获取用户资产数据
   * @param {*} callback
   * @memberof Model
   */
  async getCodexUserSymbel(obj, callback) {
    const formName = ChainModel.accountReset();
    const encodeName = Eos.modules.format.encodeName(formName, false);
    const params = {
      "lower_bound": encodeName,
      "upper_bound": encodeName,
      "code": "swap.newdex",
      "scope": obj.pair_id,
      "table": "maker",
      "json": true
    }
    if (!ChainModel.EosJsUse || ChainModel.chainName !== 'eos') {
      await ChainModel.chainNodeInit('eos')
    }
    ChainModel.EosJsUse.getTableRows(params).then(res => {
      let items = {
        pair_id: 1,
        owner: formName,
        base_quantity: `0.0000 ${obj.symbol1}`,
        quote_quantity: `0.0000 ${obj.symbol2}`,
        token: 0
      };
      if (res && res.rows && res.rows.length > 0) {
        const userItem = res.rows.find((v) => v.owner === formName);
        if (userItem) {
          items = userItem;
        }
      }
      callback(items);
    }).catch((e) => {
      this.errorCall(e, callback);
    });
  }

  /**
   * 执行 codex 兑换
  */
  async codexTransfer(obj, callback) {
    const formName = ChainModel.accountReset();
    const permission = ChainModel.accountByScatter.authority;
    const params = {
      actions: [
        {
          account: obj.contract,
          name: 'transfer',
          authorization: [{
            actor: formName, // 转账者
            permission,
          }],
          data: {
            from: formName,
            to: 'swap.newdex',
            quantity: obj.quantity,
            memo: obj.memo
          }
        }
      ]
    };
    if (!ChainModel.scatterEosJs) {
      await ChainModel.chainNodeInit('eos');
    }
    // 免费CPU
    if (obj.freeCpu) {
      ChainModel.freeCpuTransaction(params, callback);
      return;
    }
    ChainModel.scatterEosJs.transaction(params).then(callback).catch((e) => {
      ChainModel.errorCall(e, callback);
    });
  }

  /**
   * 存币合约 EOS 先转
   *  cleos --url http://192.168.8.3:8888/ push action eosio.token transfer '{"from": "zhangzhiyang","to": "swap.newdex", "quantity": "10.0000 EOS", "memo": "deposit-newdexissuer-NDX-4"}' -p zhangzhiyang
   */
  async depositTransfer(obj, callback) {
    const formName = ChainModel.accountReset();
    const permission = ChainModel.accountByScatter.authority;
    const params = {
      actions: [
        {
          account: obj.symbol2_code,
          name: 'transfer',
          authorization: [{
            actor: formName, // 转账者
            permission,
          }],
          data: {
            from: formName,
            to: 'swap.newdex',
            quantity: obj.symbol2_quantity,
            memo: `deposit-${obj.pair_id}`
          }
        },
        {
          account: obj.symbol1_code,
          name: 'transfer',
          authorization: [{
            actor: formName, // 转账者
            permission,
          }],
          data: {
            from: formName,
            to: 'swap.newdex',
            quantity: obj.symbol1_quantity,
            memo: `deposit-${obj.pair_id}`
          }
        }
      ]
    };
    if (!ChainModel.scatterEosJs) {
      await ChainModel.chainNodeInit('eos');
    }
    // 免费CPU
    if (obj.freeCpu) {
      ChainModel.freeCpuTransaction(params, callback);
      return;
    }
    ChainModel.scatterEosJs.transaction(params).then(callback).catch((e) => {
      ChainModel.errorCall(e, callback);
    });
  }

  /**
   * 取回 往流动池减少资金
    cleos --url http://192.168.8.3:8888/ push action swap.newdex withdraw  '{"pair_id":1, "owner":"zhangzhiyang",  "token": 100000}' -p zhangzhiyang
   */
  async withdraw(obj, callback) {
    const formName = ChainModel.accountReset();
    const permission = ChainModel.accountByScatter.authority;
    const params = {
      actions: [
        {
          account: 'swap.newdex',
          name: 'withdraw',
          authorization: [{
            actor: formName, // 转账者
            permission,
          }],
          data: {
            "pair_id": obj.pair_id,
            "owner": obj.owner,
            "token": obj.quNumber
          }
        },
      ]
    };
    if (!ChainModel.scatterEosJs) {
      await ChainModel.chainNodeInit('eos');
    }
    // 免费CPU
    if (obj.freeCpu) {
      ChainModel.freeCpuTransaction(params, callback);
      return;
    }
    ChainModel.scatterEosJs.transaction(params).then(callback).catch((e) => {
      ChainModel.errorCall(e, callback);
    });
  }
  /*
  * 查询swap服务状态
  */
  async swapServerStartus(obj, callback) {
    let params = {
      "code": "swap.newdex",
      "scope": "swap.newdex",
      "table": "globalconfig",
      "json": true
    };
    if (obj.symbolStatus) {
      params = {
        "code": "swap.newdex",
        "scope": "swap.newdex",
        "table": "pair",
        "json": true,
        "limit": 1500
      }
    }
    if (!ChainModel.EosJsUse || ChainModel.chainName !== 'eos') {
      await ChainModel.chainNodeInit('eos')
    }
    ChainModel.EosJsUse.getTableRows(params).then(res => callback(res)).catch((e) => {
      this.errorCall(e, callback);
    });
  }

  /*
  * 充币合约
  */
  async transactionCharging(obj, callback) {
    const formName = ChainModel.accountReset();
    const permission = ChainModel.accountByScatter.authority;
    const quantity = obj.quantity;
    const params = {
      actions: [
        {
          account: 'tethertether',
          name: 'transfer',
          authorization: [{
            actor: formName, // 转账者
            permission,
          }],
          data: {
            from: formName,
            to: 'cross.newdex',
            quantity,
            memo: ''
          }
        }
      ]
    };
    if (!ChainModel.scatterEosJs) {
      await ChainModel.chainNodeInit('eos');
    }
    if (obj.freeCpuChecked1) {
      // 免费CPU
      ChainModel.freeCpuTransaction(params, callback);
      return;
    }

    // 免费CPU 叶子钱包
    // if (ChainModel.scatapp.scatterFrom === 'leafwallet') {
    //   ChainModel.freeCpuTransaction(params, callback);
    //   return;
    // }
    ChainModel.scatterEosJs.transaction(params).then(callback).catch((e) => {
      ChainModel.errorCall(e, callback);
    });
  }
}

export var bitModel = new Model();
